package com.tbb.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AlertDialog.Builder;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Iterator;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    //定位都要通过LocationManager这个类实现
    private LocationManager locationManager;
    private String provider;

    private ProgressBar progressBar;
    private TextView textView;
    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = findViewById(R.id.progressBar);
        textView = findViewById(R.id.textView);
        mButton = findViewById(R.id.locationButton);

        progressBar.setVisibility(ProgressBar.INVISIBLE);
        textView.setText("");


        mButton.setOnClickListener(btn -> {

            //获取定位服务
            LocationManager sysLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            if ( !sysLocation.isProviderEnabled(LocationManager.GPS_PROVIDER) && !sysLocation.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

                Log.e("location","请打开系统定位功能");
                Builder builder = new Builder(MainActivity.this);

                builder.setTitle("提示");
                builder.setMessage("检测到定位功能不可用，请打开系统定位功能");
                builder.setNegativeButton("取消",(dialog,which)->{

                    Log.d("lcoation","取消打开定位");
                }).setPositiveButton("确定",(v,w)->{

                    Log.d("lcoation","打开定位");
                    startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
//                    requestLocationParams();
                });
                builder.create().show();
            } else {
                runOnUiThread(()->{
                    requestLocationParams();
                });
            }

        });

    }

    @Override
    protected void onStart() {
        super.onStart();
    }
    // 请求位置
    void requestLocationParams() {


        locationManager = null;
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        progressBar.setVisibility(ProgressBar.VISIBLE);
        textView.setText("获取位置中...");


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},1000);
            }

            progressBar.setVisibility(ProgressBar.VISIBLE);
            textView.setText("定位权限未获取");

            return;
        }

        //获取当前可用的位置控制器
        List<String> list = locationManager.getProviders(true);


        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息


        if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
            //是否为网络位置控制器

        } else if (provider.equals(LocationManager.GPS_PROVIDER)) {
            // gps 定位

            locationManager.addGpsStatusListener(new GpsStatus.Listener() {
                @Override
                public void onGpsStatusChanged(int event) {

                }
            });

            GpsStatus gpsStatus = locationManager.getGpsStatus(null);
            Iterator<GpsSatellite> it = gpsStatus.getSatellites().iterator();
            int count = 0;
            while (it.hasNext()) {
                GpsSatellite s = it.next();
                if (s.getSnr() != 0) {
                    count ++;
                }
            }

            if (count < 3) {
                runOnUiThread(()->{
                    progressBar.setVisibility(ProgressBar.INVISIBLE);
                    textView.setText("当前打开的是gps定位，无法获取到gps信息，请打开网络定位");
                });
                return;
            }

        } else {
            progressBar.setVisibility(ProgressBar.INVISIBLE);
            textView.setText("请打开蜂窝数据或者wifi连接网络，以便准确定位");
            return;
        }

//        Location location = locationManager.getLastKnownLocation(provider);

//        Location location = locationManager.getLastKnownLocation(provider);
//        if (location != null) {
//            //获取当前位置，这里只用到了经纬度
//            String string = "纬度为：" + location.getLatitude() + ",经度为："
//                    + location.getLongitude();
//            progressBar.setVisibility(ProgressBar.INVISIBLE);
//            textView.setText(string);
//        }

        //绑定定位事件，监听位置是否改变
        locationManager.requestSingleUpdate(provider, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.e("location", location.toString());
                String string = "纬度为：" + location.getLatitude() + ",经度为："
                        + location.getLongitude();
                runOnUiThread(()->{
                    progressBar.setVisibility(ProgressBar.INVISIBLE);
                    textView.setText(string);
                });
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.e("location", provider);
            }

            @Override
            public void onProviderEnabled(String provider) {
                Log.e("location", provider);
            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.e("location", provider);
            }
        }, Looper.getMainLooper());

//        locationManager.requestLocationUpdates(provider, 2000, 2, locationListener);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1000) {
            runOnUiThread(()->{
                requestLocationParams();
            });
        }
        Log.e("location", permissions.toString());
    }

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

            Log.e("location", provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            Log.e("location", provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            Log.e("location", provider);

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            // 更新当前经纬度
            Log.e("location", String.valueOf(location.getAltitude()));
            String string = "纬度为：" + location.getLatitude() + ",经度为：" + location.getLongitude();
            progressBar.setVisibility(ProgressBar.INVISIBLE);
            textView.setText(string);
        }
    };

    //关闭时解除监听器
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
        }
    }

}